package com.xuecheng.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CommentListDto;
import com.xuecheng.commons.model.dto.CourseCommentDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.system.api.SystemService;
import com.xuecheng.system.domain.User;
import com.xuecheng.teaching.domain.Comment;
import com.xuecheng.teaching.domain.CommentReply;
import com.xuecheng.teaching.mappers.CommentMapper;
import com.xuecheng.teaching.service.CommentReplyService;
import com.xuecheng.teaching.service.CommentService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者
 * @since 2022-10-10
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    //课程
    @Autowired
    private ContentClient contentClient;

    @Autowired
    private SystemService systemService;
    @Autowired
    private CommentReplyService commentReplyService;
    @Autowired
    private CommentService commentService;





    @Override
    public ResponseResult<CommentListVo> comment(CourseCommentDto dto) {

//        查询课程
//        LambdaQueryWrapper<CourseRecord>wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(CourseRecord::getCoursePubId,dto.getTargetId());
        ResponseResult<CoursePubVo> clientById = contentClient.findById(Long.valueOf(dto.getTargetId()));
        CoursePubVo data = clientById.getData();
//        评论名称-课程名
        String name = data.getName();
        Long userId = AuthInfoHolder.getUserId();
//        userService.userService
        ResponseResult<User> userData = systemService.findByid(userId);
        User user = userData.getData();
        String nickName = user.getName();
        String phone = user.getUserpic();
        Comment vo=new Comment();
        //查询课程发布ID
        ResponseResult<CoursePubVo> clientById1 = contentClient.findById(Long.valueOf(dto.getTargetId()));
//        /课程发布信息
        CoursePubVo coursePubVo = clientById1.getData();
        //判断课程id查询是否为空
        if (ObjectUtils.isEmpty(coursePubVo)) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //评论对象id，课程id
        vo.setTargetId(coursePubVo.getId());
        //评论名称,课程名称
        vo.setTargetName(coursePubVo.getName());
      //评论来源那个项目
        vo.setComeFrom(coursePubVo.getName());
        //企业id
//        vo.setCompanyId(coursePubVo.getCompanyId());
//        vo.setTargetName(data.getCompanyName());
        vo.setUserId(userId);
        vo.setUserName(nickName);
        vo.setNickName(nickName);
        vo.setUserHead(phone);
        vo.setCommentText(dto.getCommentText());
        vo.setCommentDate(new Date());
        vo.setStarRank(dto.getStarRank());
        vo.setStatus(1);
        vo.setBelongTo(data.getCompanyId());

        vo.setForbidReply(1);//1允许 0,禁止

//        点赞数量=查询reply表的相同id；；；不会 就很尴尬
        boolean save = this.save(vo);
        if (!save){
            throw new BusinessException(ErrorCode.ERROR);
        }
        CommentListVo commentListVo = BeanHelper.copyProperties(vo, CommentListVo.class);

        commentListVo.setBelongTo(dto.getCommentId());
//        commentListVo.setTargetType();不知道是啥
   /*
   * //        表里的查询评论部分
   * */
   dto.getCommentId();

        LambdaQueryWrapper<CommentReply> wrapper = new LambdaQueryWrapper<>();
        //机构的id
        wrapper.eq(CommentReply::getCommentId, AuthInfoHolder.getCompanyId());
        //评论id
        wrapper.eq(CommentReply::getParentId, commentListVo.getCommentId());
           /* //课程id
            wrapper1.eq(CommentReply::getParentId, dto.getTargetId());*/
        //查询
        List<CommentReply> commentReplies = commentReplyService.list(wrapper);
        List<ReplyDTOList> commentVos = BeanHelper.copyWithCollection(commentReplies, ReplyDTOList.class);
//        //判断长度!=0的话就有人评论
        commentListVo.setReplyDTOList(commentVos);

        return ResponseResult.okResult(commentListVo);
    }
//回复评论列表
    /*
    * 查询课程名，根据课程名查所有评论，根据每一条评论获取用户名和用户id，
    * 根据评论回复表里的comment_id 查回复数据
    * */
    @Override
    public ResponseResult<List<CommentListVo>> commentlist(CommentListDto dto)  {


//创建分页对象
        Page<Comment>page=new Page<>(dto.getPageNo(),dto.getPageSize());
//        构建查询条件 查询课程名，根据课程名查所有评论，
        LambdaQueryWrapper<Comment>wrapper=new LambdaQueryWrapper<>();
//        查询课程名
        if (!StringUtils.isEmpty(dto.getTargetId())) {
            wrapper.eq(Comment::getTargetId, dto.getTargetId());
        }
// 星级好评，4-5星好评(1) 2-3星中评(0)，1星差评(-1)
        if (!StringUtils.isEmpty(dto.getLevel())) {
            int level = dto.getLevel();

            if (!StringUtils.isEmpty(level)) {
//            好评
                if (level == 1) {
                    wrapper.eq(Comment::getStarRank, 4).or().eq(Comment::getStarRank, 5);
                }
//            中评
                if (level == 0) {
                    wrapper.eq(Comment::getStarRank, 3).or().eq(Comment::getStarRank, 2);
                }
//            差评
                if (level == -1) {
                    wrapper.eq(Comment::getStarRank, 1);
                }
            }
        }
        //        查询回复状态
        if (!StringUtils.isEmpty(dto.getReplyStatus())){
            wrapper.eq(Comment::getReplyStatus,dto.getReplyStatus());
        }
        //        查询课程名
        if (!StringUtils.isEmpty(dto.getTargetId())){
            wrapper.eq(Comment::getTargetId,dto.getTargetId());
        }
//        插叙评论对象
        if (!StringUtils.isEmpty(dto.getTargetName())){
            wrapper.eq(Comment::getTargetName,dto.getTargetName());
        }
        //请求查询

        page = commentService.page(page, wrapper);
        long total = page.getTotal();
        List<Comment> records = page.getRecords();

        //        数据返回
        List<CommentListVo> listVos = BeanHelper.copyWithCollection(records, CommentListVo.class);
//        循环评论
        for (CommentListVo listVo : listVos) {
//            在评论中循环一下 查回复
            ReplyDTOList   replyDTOList=null;
            for (Comment comment : records) {
//如果有回复 将恢复内容返回
                if (StringUtils.isEmpty(dto.getReplyStatus())) {
                    LambdaQueryWrapper<CommentReply> replyWrapper = new LambdaQueryWrapper<>();
                    replyWrapper.eq(CommentReply::getCommentId, comment.getId());
                    replyWrapper.eq(CommentReply::getStatus, 1);//1显示  0隐藏
                    List<CommentReply> commentReplyList = commentReplyService.list(replyWrapper);
                    replyDTOList= BeanHelper.copyProperties(commentReplyList, ReplyDTOList.class);
                }
            }
            ArrayList<ReplyDTOList> list = new ArrayList<>();
            list.add(replyDTOList);
            listVo.setReplyDTOList(list);
        }
        return new PageResponseResult(total,listVos);
    }

    //教育机构---分页查询评论列表


//   门户   课程评论统计
    @Override
    public ResponseResult<StarRankVo>  courseReplyStatistical(long targetId) {
//        根据课程id查询信息
//        LambdaQueryWrapper<CoursePubVo>wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(CoursePubVo::getId,targetId);
//        wrapper.eq(CoursePubVo::getIsPub,0);//0是发布，1是未发布
        ResponseResult<CoursePubVo> byId = contentClient.findById(targetId);
        CoursePubVo data = byId.getData();
//        课程名
        String name = data.getName();
//        根据课程id查评论数量
        LambdaQueryWrapper<Comment>wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getTargetId,targetId);

        List<Comment> list = commentService.list(wrapper);
//        总计评价数量
        int size = list.size();
//        查询评星
        LambdaQueryWrapper<Comment>star1=new LambdaQueryWrapper<>();
        star1.eq(Comment::getTargetId,targetId);
        star1.eq(Comment::getStarRank,1);
        int count1 = Math.toIntExact(commentService.count(star1));
//        一星

        //        查询评星2
        LambdaQueryWrapper<Comment>star2=new LambdaQueryWrapper<>();
        star2.eq(Comment::getTargetId,targetId);
        star2.eq(Comment::getStarRank,2);
        int count2 = Math.toIntExact(commentService.count(star2));
//        一星
        //        查询评星3
        LambdaQueryWrapper<Comment>star3=new LambdaQueryWrapper<>();
        star3.eq(Comment::getTargetId,targetId);
        star3.eq(Comment::getStarRank,3);
        int count3 = Math.toIntExact(commentService.count(star3));

        //        查询评星4
        LambdaQueryWrapper<Comment>star4=new LambdaQueryWrapper<>();
        star4.eq(Comment::getTargetId,targetId);
        star4.eq(Comment::getStarRank,4);
        int count4 = Math.toIntExact(commentService.count(star4));

        //        查询评星5
        LambdaQueryWrapper<Comment>star5=new LambdaQueryWrapper<>();
        star5.eq(Comment::getTargetId,targetId);
        star5.eq(Comment::getStarRank,5);
        int count5 = Math.toIntExact(commentService.count(star5));
// 所有评价条数
        Integer all=count1+count2+count3+count4+count5;
//        平均星
       String aver= String.valueOf((count1+count2*2+count3*3+count4*4+count5*5)/all);

        StarRankVo rankVo = new StarRankVo();
        rankVo.setStarRank(aver);//平均星
        rankVo.setStarRank1Nums(count1);
        rankVo.setStarRank2Nums(count2);
        rankVo.setStarRank3Nums(count3);
        rankVo.setStarRank4Nums(count4);
        rankVo.setStarRank5Nums(count5);
        rankVo.setTotalCommentNums(all);
        rankVo.setTargetId(Math.toIntExact(targetId));
//        返回
        return ResponseResult.okResult(rankVo);
    }
//    评论列表
    @Override
    public ResponseResult<CommentListVo> forlist(CommentListDto dto, PageRequest request) {


//创建分页对象
        Page<Comment>page=new Page<>(request.getPageNo(),request.getPageSize());
//        构建查询条件 查询课程名，根据课程名查所有评论，
        LambdaQueryWrapper<Comment>wrapper=new LambdaQueryWrapper<>();
//        查询课程名
        if (!StringUtils.isEmpty(dto.getTargetId())) {
            wrapper.eq(Comment::getTargetId, dto.getTargetId());
        }
// 星级好评，4-5星好评(1) 2-3星中评(0)，1星差评(-1)
        if (!StringUtils.isEmpty(dto.getLevel())) {
            int level = dto.getLevel();

            if (!StringUtils.isEmpty(level)) {
//            好评
                if (level == 1) {
                    wrapper.eq(Comment::getStarRank, 4).or().eq(Comment::getStarRank, 5);
                }
//            中评
                if (level == 0) {
                    wrapper.eq(Comment::getStarRank, 3).or().eq(Comment::getStarRank, 2);
                }
//            差评
                if (level == -1) {
                    wrapper.eq(Comment::getStarRank, 1);
                }
            }
        }
        //        查询回复状态
        if (!StringUtils.isEmpty(dto.getReplyStatus())){
            wrapper.eq(Comment::getReplyStatus,dto.getReplyStatus());
        }
        //        查询课程名
        if (!StringUtils.isEmpty(dto.getTargetId())){
            wrapper.eq(Comment::getTargetId,dto.getTargetId());
        }
//        插叙评论对象
        if (!StringUtils.isEmpty(dto.getTargetName())){
            wrapper.eq(Comment::getTargetName,dto.getTargetName());
        }
        //请求查询

        page = commentService.page(page, wrapper);
        long total = page.getTotal();
        List<Comment> records = page.getRecords();

        //        数据返回
        List<CommentListVo> listVos = BeanHelper.copyWithCollection(records, CommentListVo.class);
//        循环评论
        for (CommentListVo listVo : listVos) {
//            在评论中循环一下 查回复
            ReplyDTOList   replyDTOList=null;
            for (Comment comment : records) {
//如果有回复 将恢复内容返回
                if (StringUtils.isEmpty(dto.getReplyStatus())) {
                    LambdaQueryWrapper<CommentReply> replyWrapper = new LambdaQueryWrapper<>();
                    replyWrapper.eq(CommentReply::getCommentId, comment.getId());
                    replyWrapper.eq(CommentReply::getStatus, 1);//1显示  0隐藏
                    List<CommentReply> commentReplyList = commentReplyService.list(replyWrapper);
                    replyDTOList= BeanHelper.copyProperties(commentReplyList, ReplyDTOList.class);
                }
            }
            ArrayList<ReplyDTOList> list = new ArrayList<>();
            list.add(replyDTOList);
            listVo.setReplyDTOList(list);
        }

        return new PageResponseResult(total,listVos);
    }

    @Override
    public PageResponseResult<CommentListVo> listAll(CommentListDto dto) {
        Page<Comment> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        //所有数据
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        //倒叙查询
        wrapper.orderByDesc(Comment::getId);
        Page<Comment> page1 = this.page(page, wrapper);
        List<Comment> records = page1.getRecords();
        List<CommentListVo> courseCommentVos = new ArrayList<>();
        for (Comment record : records) {
            CommentListVo commentVo = BeanHelper.copyProperties(record, CommentListVo.class);
            Integer commentId = Integer.valueOf(record.getId() + "");
            commentVo.setCommentId(commentId);
            Integer belongTo = Integer.valueOf(record.getBelongTo() + "");
            commentVo.setBelongTo(belongTo);
            //时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateFormat.format(record.getCommentDate());
            commentVo.setCommentDate(format);
            commentVo.setTargetId(Integer.valueOf(record.getTargetId() + ""));
            commentVo.setTargetType(record.getTargetType() + "");
            //头像
            commentVo.setUserHead(record.getUserHead());
            commentVo.setUserId(Integer.valueOf(record.getUserId() + ""));
            //查询回复评论表
            LambdaQueryWrapper<CommentReply> wrapper1 = new LambdaQueryWrapper<>();
            //机构的id
            // wrapper1.eq(CommentReply::getCommentId, AuthInfoHolder.getCompanyId());
            //评论id
            wrapper1.eq(CommentReply::getParentId, commentVo.getCommentId());
            //查询
            List<CommentReply> commentReplies = commentReplyService.list(wrapper1);
            //

            List<ReplyDTOList> commentReplyVos = new ArrayList<>();
            ReplyDTOList commentReplyVo = new ReplyDTOList();
            //遍历
            for (CommentReply commentReply : commentReplies) {
                //评论id转String在转Integer
                String tCommentId = commentReply.getCommentId() + "";
                Integer integer = Integer.valueOf(tCommentId);
                //评论id
                commentReplyVo.setCommentId(integer);
                //是否禁止1禁止0允许
                commentReplyVo.setForbidReply(commentReply.getForbidReply());
                //用户昵称
                commentReplyVo.setNickName(commentReply.getNickName());
                //回复父id
                //转String在转Integer
                String ParentId = commentReply.getParentId() + "";
                Integer ParentId1 = Integer.valueOf(ParentId);
                commentReplyVo.setParentId(ParentId1);
                //点赞数量
                commentReplyVo.setPraiseNum(commentReply.getPraiseNum());
                //回复时间
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = dateFormat1.format(commentReply.getReplyDate());
                commentReplyVo.setReplyDate(date);
                //回复内容
                commentReplyVo.setReplyText(commentReply.getReplyText());
                //回复id
                //转String在转Integer
                String UserId = commentReply.getUserId() + "";
                Integer UserId1 = Integer.valueOf(UserId);
                commentReplyVo.setUserId(UserId1);
                //用户名
                commentReplyVo.setUserName(commentReply.getUserName());
                commentReplyVos.add(commentReplyVo);
            }
            //判断长度!=0的话就有人评论
            commentVo.setReplyDTOList(commentReplyVos);
            courseCommentVos.add(commentVo);
        }
        long total = page1.getTotal();
        return new PageResponseResult(total, courseCommentVos);
    }


//    删除
    @Override
    public ResponseResult delete(long commentId) {
        //判断id是否为空
        if (ObjectUtils.isEmpty(commentId)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
//        //查询工具id查询是否存在
        Comment comment = this.getById(commentId);
        if (ObjectUtils.isEmpty(comment)) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        boolean b = this.removeById(commentId);
        if (!b){
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        return ResponseResult.okResult();
    }


}
